package com.msh.frame.common.logback;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.boolex.EventEvaluatorBase;


public class CounterEvaluator extends EventEvaluatorBase<ILoggingEvent> {

  /**
   * 10个error发一次邮件
   */
  final private static int LIMIT = 10;

  /**
   * 当前积攒了多少error
   */
  private int counter = 0;

  /**
   * 最后一次发送的时间
   */
  private long lastSendTime = System.currentTimeMillis();

  /**
   * 间隔  默认10分钟
   */
  private final Long INTERVAL = 1000 * 60 * 10L;

  /**
   * @see ch.qos.logback.core.boolex.EventEvaluator#evaluate(Object)
   */
  @Override
  public boolean evaluate(ILoggingEvent event) {
    counter++;
    long now = System.currentTimeMillis();
    //时间间隔超过 默认间隔时间 重置counter为第一次,返回false
    if (now - lastSendTime > INTERVAL) {
      lastSendTime = now;
      counter = 1;
      return false;
    }
    lastSendTime = now;
    //累计计数小于限制次数，返回false
    if (counter < LIMIT) {
      return false;
    }
    counter = 0;
    return true;
  }
}
